package com.gla.market.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoadPictureActivity extends AppCompatActivity {

    Button load_picture,load_camera,back;
    ImageView head;

    public static final int REQUEST_CODE_CAMERA = 1;
    public Uri imageUri;
    public File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_picture);
        initView();
        load_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //启动相机
                startCamera();
//                //加载图片到imageview中
//                try {
//                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                    head.setImageBitmap(bitmap);
//                    //bitmap转为文件
//                    file = bitmap2File(bitmap);
//                    NetUtil.upload(Constants.BASE_URL+Constants.UPLOAD_PICTURE_URL, file.getAbsolutePath(), new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                        }
//                        @Override
//                        public void onResponse(Call call, Response response) throws IOException {
//                            Log.d("com.petshop","123");
//                        }
//                    });
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoadPictureActivity.this,PerSettingActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    private void initView() {
        load_picture = findViewById(R.id.load_picture);
        load_camera = findViewById(R.id.load_camera);
        back = findViewById(R.id.back1);
        head = findViewById(R.id.head);
//        imageUri = (Uri) SharedPreferencesUtil.get(this,"userPic","user_photo",1);
    }

    //bitmap转文件
    public File bitmap2File(Bitmap bm){
        BufferedOutputStream bos = null;
        try{
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
            bos.flush();
            bos.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    //启动相机
    public void startCamera(){
        //通过隐式intent启动相机服务
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        //构建存储图片的临时目录imageuri
        intent.putExtra(MediaStore.EXTRA_OUTPUT,getImageUri(getFile()));
        startActivityForResult(intent,REQUEST_CODE_CAMERA);
    }

    //获取图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //判断时当前activity启动的相机
        if (requestCode == REQUEST_CODE_CAMERA){
            if (requestCode == RESULT_OK){
                crop(imageUri);//图片裁剪
//                try {
                        // 通过读取uri里的内容加载图片
//                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                    head.setImageBitmap(bitmap);//将bitmap加载在控件上
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
            }else if(requestCode == PHOTO_REQUEST_CUT){
                if (data != null){
                    Bitmap bitmap =data.getParcelableExtra("data");
                    head.setImageBitmap(bitmap);
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    //得到文件（拍照存放的目录）
    public File getFile(){
        file = new File(getExternalCacheDir(),"temp_photo.png");//保存在SD卡中，名为temp_
        if (file.exists()){
            file.delete();//若存在将文件删除
        }try{
            file.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }
    //得到Uri
    public Uri getImageUri(File file){
        //根据当前手机版本判断
        if (Build.VERSION.SDK_INT >= 24){
            //通过FileProvider获取imageuri
            imageUri = FileProvider.getUriForFile(this,"com.gla.market.fileprovider", file);
        }else{
            //直接传文件得到imguri
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }
    public static final int PHOTO_REQUEST_CUT = 10;
    //裁剪图片
    public void crop(Uri uri){
        Intent intent = new Intent("com.android.camera.action.CROP");
        //读写权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //添加数据
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        //裁剪框比例1：1
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        //裁剪后输出图片的尺寸大小
        intent.putExtra("outputX",200);
        intent.putExtra("outputY",200);

        intent.putExtra("outputFormat","JPEG");//图片格式
        intent.putExtra("noFaceDEtection",true);//取消人脸识别
        intent.putExtra("return-data",true);
        //开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent,PHOTO_REQUEST_CUT);
    }
}